package com.education.teach.mvp.presenter;

import android.app.Application;
import android.widget.Toast;

import com.education.teach.mvp.contract.ExamContract;
import com.education.teach.mvp.model.bean.ExamBean;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


@ActivityScope
public class ExamPresenter extends BasePresenter<ExamContract.Model, ExamContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public ExamPresenter(ExamContract.Model model, ExamContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void findMyHomeWork(String xsXlh, int page, int maxRow, boolean isRefreh) {
        Map<String, String> map = new HashMap<>();
        map.put("xsxlh", xsXlh);
        map.put("currentPage", page + "");
        map.put("maxRows", maxRow + "");
        mModel.findMyHomeWork(map)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
        .doOnSubscribe(disposable -> mRootView.showLoading())
        .doFinally(() -> mRootView.hideLoading())
        .subscribe(new ErrorHandleSubscriber<ExamBean>(mErrorHandler) {
            @Override
            public void onNext(ExamBean examBean) {
                if(examBean.getCode() == 0){
                    if (isRefreh) {
                        mRootView.returnRefreshExamList(examBean.getResult().getQueryList());
                    }else {
                        mRootView.returnLoadMoreExamList(examBean.getResult().getQueryList());
                    }
                }else {
                    Toast.makeText(mApplication, "服务器异常，请稍后再试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
